using System;
using System.Collections.Generic;
using Arcane.Source.Client.Extensions;
using Arcane.Source.Data;
using Godot;

using static Arcane.Source.GameContext;

namespace Arcane.Source.Client
{
    public partial class CharaPickView : Control, IView
    {
        [Export]
        private PackedScene _cardPrefab;
        [Export]
        private Control _cardMnt;

        public Node Node => null;
        public Control UI => this;
        public GameOS Os { private get; set; }

        public Color? ClearColor => Colors.DimGray;

        public GameContext Context { private get; set; }

        private readonly List<Control> _charaCards = [];
        private readonly List<StringName> _charaIds = [];

        public int Selection { get; private set; }
        public Control CurrentCard => _charaCards[Selection];


        // public event Action<StringName> OnPick;

        public override void _Ready()
        {
            _cardMnt.QueueFreeChildren();
        }

        public void LoadCharacters(IEnumerable<KeyValuePair<StringName, CharacterData>> charaData)
        {
            ClearCache();

            foreach (var (name, data) in charaData)
            {
                var card = _cardPrefab.Instantiate<Control>();
                card.GetNode<Label>("Contents/Label").Text = data.name;
                _charaIds.Add(name);
                _charaCards.Add(card);
            }

            Select(0);
        }

        public void Select(int selection)
        {
            if (_charaCards.Count <= 0) return;

            Selection = selection % _charaCards.Count;

            _cardMnt.RemoveChildren();
            _cardMnt.AddChild(CurrentCard);
        }

        public void Next() => Select(Selection + 1);
        public void Prev() => Select(Selection - 1);

        private void OnPickButtonUp()
        {
            Os.EventHub.SendEvent<GameContext, IGameEvent>(new CharaPickedEvent(_charaIds[Selection]));
        }

        private void ClearCache(object _ = null)
        {
            foreach (var cards in _charaCards)
            {
                cards.QueueFree();
            }
            _charaCards.Clear();
            _charaIds.Clear();
        }
    }
}